package com.yaolaizaixian.merchant.order;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.adapter.OrderListAdapter;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.OrderData;
import com.yaolaizaixian.merchant.bean.OrderList;
import com.yaolaizaixian.merchant.bean.OrderListModel;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by ylzx on 2017/3/7.
 * 订单扫码结果界面
 */
public class SweepResultActivity extends BaseActivity {


    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.xrv_searchorderlist)
    XRecyclerView xrvSearchorderlist;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_kong)
    ImageView ivKong;
    @BindView(R.id.rl_kong)
    AutoRelativeLayout rlKong;
    private ArrayList<OrderList> totalorderLists;
    private OrderListAdapter orderListAdapter;

    private int pageNum = 1;
    private String userId;

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {
                        final OrderListModel orderListModel = GsonUtil.jsonToBean(result, OrderListModel.class);
                        OrderData orderData = orderListModel.getData();
                        orderLists = orderData.getList();
                        if (null != orderLists && orderLists.size() > 0) {

                            totalorderLists.addAll(orderLists);
                        }
                        if (totalorderLists.size() <= 0) {
                            rlKong.setVisibility(View.VISIBLE);
                        } else {
                            rlKong.setVisibility(View.GONE);
                        }

                        if (null == orderListAdapter) {
                            orderListAdapter = new OrderListAdapter(SweepResultActivity.this, totalorderLists, "2");

                            xrvSearchorderlist.setAdapter(orderListAdapter);

                        } else {

                            orderListAdapter.notifyDataSetChanged();

                        }
                        if (pageNum == 1) {
                            tvTime.setVisibility(View.GONE);
                            xrvSearchorderlist.refreshComplete();

                        } else {
                            xrvSearchorderlist.loadMoreComplete();
                        }

                        orderListAdapter.setOnItemClickListener(new OrderListAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
//                                完成补录状态(0:需补录，1:已完成)
                                if (!TextUtils.isEmpty(totalorderLists.get(position).getIsDitional()) && "0".equals(totalorderLists.get(position).getIsDitional()) && "15".equals(totalorderLists.get(position).getStatus())) {


                                    Intent intent = new Intent(SweepResultActivity.this, MakeUpInfoActivity.class);

                                    intent.putExtra("orderlifeid", totalorderLists.get(position).getLife_so_master_id());
                                    intent.putExtra("ordersysno", totalorderLists.get(position).getSysno());
                                    intent.putExtra("sign", "1");
                                    startActivityForResult(intent, 99);
//                                    startActivity(intent);

                                } else if (!TextUtils.isEmpty(totalorderLists.get(position).getIsDitional()) && "0".equals(totalorderLists.get(position).getIsDitional())) {
                                    Toasty.error(SweepResultActivity.this, "订单未完成", Toast.LENGTH_SHORT, true).show();
                                }

                            }

                            @Override
                            public void onLongClick(int position) {

                            }
                        });


                    } else {

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            showConflictDialog(SweepResultActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(SweepResultActivity.this, "您的账号在其它设备登录");

                        } else {
                            rlKong.setVisibility(View.VISIBLE);
                            Toast.makeText(SweepResultActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;
                        }

                    }
                    break;


            }
        }
    };
    private List<OrderList> orderLists;
    private String phone;

    @Override
    public void initView() {
        setContentView(R.layout.activity_sweepresult);

        totalorderLists = new ArrayList<>();
    }

    @Override
    public void initData() {
        tvTitleText.setText("搜索结果");

        LinearLayoutManager layoutManager = new LinearLayoutManager(SweepResultActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xrvSearchorderlist.setLayoutManager(layoutManager);
        xrvSearchorderlist.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrvSearchorderlist.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        xrvSearchorderlist.setArrowImageView(R.mipmap.iconfont_downgrey);

        //用户id
        userId = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");
        phone = getIntent().getStringExtra("phone");

        //上拉刷新
        xrvSearchorderlist.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum = 1;
                        totalorderLists.clear();
                        getData(pageNum + "", phone);


                    }

                }, 1000);

            }

            //加载更多
            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum += 1;
                        getData(pageNum + "", phone);

                    }
                }, 1000);


            }
        });

        tvTime.setVisibility(View.GONE);

        xrvSearchorderlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                View stickyInfoView = recyclerView.findChildViewUnder(
                        tvTime.getMeasuredWidth() / 2, 5);

                if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
                    tvTime.setText(String.valueOf(stickyInfoView.getContentDescription()));
                }

                View transInfoView = recyclerView.findChildViewUnder(
                        tvTime.getMeasuredWidth() / 2, tvTime.getMeasuredHeight() + 1);

                if (transInfoView != null && transInfoView.getTag() != null) {

                    int transViewStatus = (int) transInfoView.getTag();
                    int dealtY = transInfoView.getTop() - tvTime.getMeasuredHeight();

                    if (transViewStatus == orderListAdapter.FIRST_STICKY_VIEW) {
                        tvTime.setVisibility(View.GONE);
                    } else {
                        tvTime.setVisibility(View.VISIBLE);
                    }

                    if (transViewStatus == orderListAdapter.HAS_STICKY_VIEW) {
                        if (transInfoView.getTop() > 0) {
                            tvTime.setTranslationY(dealtY);
                        } else {
                            tvTime.setTranslationY(0);
                        }
                    } else if (transViewStatus == orderListAdapter.NONE_STICKY_VIEW) {
                        tvTime.setTranslationY(0);

                    }
                }
            }
        });

        setselect();


    }

    private void setselect() {

        pageNum = 1;

        //隐藏空数据
        rlKong.setVisibility(View.GONE);

        if (null != totalorderLists && totalorderLists.size() > 0) {

            totalorderLists.clear();
            orderLists.clear();
            //获取数据
            getData(pageNum + "", phone);
            orderListAdapter.notifyDataSetChanged();

        } else {

            //获取数据
            getData(pageNum + "", phone);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 99) {
            //刷新
            setselect();
        }

    }

    /**
     * 获取订单数据
     * userId		用户ID
     * phoneOrSoId	订单号或手机号
     * pageNum	页码
     * pageSize
     */
    private void getData(String pageNum, String phoneOrSoId) {
        //店铺id
        String shopsysno = SharedPreferencesUtil.getString(this, "shopsysno", "");
        try {

            final String url = BaseInfo.URL + "lifeOrder/searchMySalesListByID.do";
            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            sortedParams.put("pageSize", "10");
            sortedParams.put("pageNum", pageNum);
            sortedParams.put("phoneOrSoId", phoneOrSoId);
            sortedParams.put("userId", userId);
            sortedParams.put("shopStoreSysno", shopsysno);

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {
            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.ll_back)
    public void onClick() {
        finish();
    }
}
